package com.module.codeBind.manager;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.Transaction;

import base.common.CUDEnum;
import base.dao.GenericHibernateDao;
import base.db.HibernateSessionFactory;
import base.manager.GenericHibernateManager;
import base.util.ConstantUnit;
import base.util.JsonMsg;
import base.util.Page;
import base.util.StringUtil;
import base.util.transaction.TransactionCallback;
import base.util.transaction.TransactionTemplate;

import com.module.codeBind.dao.BatchCodeDao;
import com.module.codeBind.dao.BindBatchCodeDao;
import com.module.codeBind.vo.BatchCode;
import com.module.codeBind.vo.CodeBind;



public class BatchCodeManager  extends GenericHibernateManager<BatchCode,String> implements ConstantUnit{

	private static BatchCodeManager manager;
	private static BatchCodeDao dao = BatchCodeDao.getInstance();
    private BindBatchCodeDao bindBatchCodeDao = BindBatchCodeDao.getInstance();
	
    private BatchCodeManager(){}
	
	public synchronized static BatchCodeManager getInstance(){
		  if(manager==null){
			  manager = new BatchCodeManager();
		  }
		return manager;
	}
	/**
	 * 保存贴码信息
	 * @param bean
	 * @return
	 */
	public Map<String,Object> saveBatchCode(final BatchCode bean){
		final Session session =HibernateSessionFactory.getSession();
		if(!StringUtil.isNull(bean.getId())){
			bean.setUpdateTime(new Date());
			bean.setStatus(CUDEnum.U.toString());
		}else {
			bean.setCreateTime(new Date());
			bean.setStatus(CUDEnum.C.toString());
		}
		//状态为非立即开通;
		if(bean.getOpenType()!=null && bean.getOpenType().intValue()!=1){
			if(bean.getOpenTime() == null){
				bean.setBatchCodeState(1);
			}else if(bean.getOpenTime().after(new Date())){
				bean.setBatchCodeState(1);
			}
		}
		    final BatchCode bc = new BatchCode();
			final TransactionTemplate template = new TransactionTemplate(session);
			template.execute(new TransactionCallback() {
				@Override
				public void doInTransaction() {
				   JsonMsg msg = dao.saveBatchCode(session,bean);
				   template.setJsonMsg(msg);
				   bc.setItems(bean.getItems());
				}
			});
		Map<String,Object> map = new HashMap<String,Object>();
		map = template.getJsonMsg().getMap();
		if((Boolean) map.get("state")){
			map.put("batchCode", bc);
		}
		return map;
	}
	/**
	 * 查询贴码信息列表
	 * @param bean
	 * @param page
	 * @return
	 */
	public Page toListBatchCode(BatchCode bean,Page page) throws Exception{
		Session session =HibernateSessionFactory.getSession();
		try{
			page = dao.getList(session,bean,bean.getRollNum(),bean.getSequenceNum(),page.getStart(), page.getLimit());

    	}catch(Exception e){
    		throw e;
    	}finally{
    		this.closeSession();
    	}
		return page;
	}
	/**
	 * 根据ID查询对象
	 * @param id
	 * @return 批次对象
	 * @throws Exception
	 */
	public BatchCode findByIdBatchCode(String id) throws Exception{
		Session session =HibernateSessionFactory.getSession();
		BatchCode bean = new BatchCode();
		try{
			bean = dao.findById(session,id);
    	}catch(Exception e){
    		throw e;
    	}finally{
    		this.closeSession();
    	}
		return bean;
	}
	/**
	 * 删除贴码信息
	 * @param bean
	 * @param idArray
	 * @return
	 */
	public Map<String,Object> deleteBatchCode(final BatchCode bean,final List idArray){
		
		final Session session =HibernateSessionFactory.getSession();
		Map<String,Object> map = new HashMap<String,Object>();
		final TransactionTemplate template = new TransactionTemplate(session);
			boolean canDelete = bindBatchCodeDao.hasBatchCode4Bind(session,idArray);
			if(canDelete){
				template.getJsonMsg().setFailMsg("已绑定应用，不能删除");
				map = template.getJsonMsg().getMap();
				return map;
			}
			template.getJsonMsg().setMsg("\u5220\u9664\u6210\u529f");//删除成功
			template.execute(new TransactionCallback() {
				@Override
				public void doInTransaction() {
					
					dao.deleteBatchCode(session,idArray,bean.getUpdaterId());
				}
			});
			map = template.getJsonMsg().getMap();
    	
		return map;
	}
	/**
	 * 根据商品获取批次号
	 * @param bean
	 * @param bind
	 * @return
	 * @throws Exception
	 */
	public List comboListBatchCode(final BatchCode bean,final CodeBind bind) throws Exception{
		List list  = null;
		Session session =HibernateSessionFactory.getSession();
		try{
				list = (dao.getList(session,bean,bind.getId()));
	    	}catch(Exception e){
	    		throw e;
	    	}finally{
	    		this.closeSession();
	    	}
		return list;
	}

	/**
	 * 开启定时类型的批次
	 * @return
	 * @throws Exception
	 */
	public Map<String,Object> openBatchByTime() throws Exception{

		Session session =HibernateSessionFactory.getSession();
		Transaction tx =session.beginTransaction();
		boolean flag = false;
		try{
	    		flag = dao.openBatchByTime(session);
	    		tx.commit();
	    		Map map = RequestManager.addOptReturnMessage(flag);
	    		return map;
	    	}catch(Exception e){
	    		if(tx!=null)
	    			tx.rollback();
	    		throw e;
	    	}finally{
	    		this.closeSession();
	    	}
	}

	/**
	 * 手动开通
	 * @param idArray
	 * @return
	 * @throws Exception
	 */
	public Map<String,Object>  openBatchByHand (final List idArray) throws Exception{

		Session session =HibernateSessionFactory.getSession();
		Transaction tx =session.beginTransaction();
		boolean flag = false;
		try{
	    		flag = dao.openBatchByHand(session,idArray);
	    		tx.commit();
	    		Map map = RequestManager.addOptReturnMessage(flag);
	    		return map;
	    	}catch(Exception e){
	    		if(tx!=null)
	    			tx.rollback();
	    		throw e;
	    	}finally{
	    		this.closeSession();
	    	}
	}

	@Override
	public GenericHibernateDao<BatchCode, String> getDao() {
		// TODO Auto-generated method stub
		return dao;
	}
}
